
package com.sxtyxt.online.imagecrop;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

import com.sxtyxt.online.ActBase;
import com.sxtyxt.online.R;
import com.sxtyxt.util.FileUtil;
import com.sxtyxt.util.ImageUtil;

import android.content.Intent;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;


public class ActClipImage extends ActBase {

	public static final int CLIPIMAGE = 231;
	private ClipImageLayout mClipImageLayout;
	private TextView txt_ok;

	@Override
	protected int getLayoutId() {

		return R.layout.clip_image;
	}

	@Override
	protected void initUI() {

		super.initUI();
		mClipImageLayout = (ClipImageLayout) findViewById(R.id.id_clipImageLayout);

		String filePath = getIntent().getStringExtra("PATH");
		mClipImageLayout.setImageBitmap(ImageUtil.getImage(filePath));

		txt_ok = (TextView) findViewById(R.id.txt_ok);
		txt_ok.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Bitmap bitmap = mClipImageLayout.clip();
				String path = saveBitmapFile(bitmap);

				if (TextUtils.isEmpty(path)) {
					return;
				}

				Intent intent = new Intent();
				intent.putExtra("bitmap", path);
				setResult(RESULT_OK, intent);
				finish();
			}
		});

	}

	public String saveBitmapFile(Bitmap bitmap) {
		String path = FileUtil.getSDImagePath();
		if (path == null) {
			return null;
		}

		String strImgPath = path
		        + UUID.randomUUID().toString().replaceAll("-", "") + ".jpg";
		File file = new File(strImgPath);
		try {
			BufferedOutputStream bos = new BufferedOutputStream(
			        new FileOutputStream(file));
			bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
			bos.flush();
			bos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return strImgPath;
	}

}
